// Works管理相关功能模块

let currentEditingWorkId = null;

// 加载Works列表
function loadWorksList() {
    // 尝试从缓存获取数据
    const cachedWorks = dataCache.getCache('works');
    if (cachedWorks) {
        renderWorksList(cachedWorks);
        return;
    }
    
    fetch('../BlogMake.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
        },
        body: 'action=get_works_list'
    })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                let worksList = data.data || [];
                
                // 更新缓存
                dataCache.updateCache('works', worksList);
                
                renderWorksList(worksList);
                showStatus('作品列表加载成功', 'success');
            } else {
                showStatus('加载作品列表失败: ' + data.message, 'error');
            }
        })
        .catch(error => {
            console.error('加载作品列表失败:', error);
            showStatus('加载作品列表失败', 'error');
        });
}

// 渲染Works列表
function renderWorksList(worksList) {
    const worksListContainer = document.getElementById('works-list');

    // 清空列表
    worksListContainer.innerHTML = '';

    if (worksList.length === 0) {
        worksListContainer.innerHTML = `
            <div class="placeholder">
                <i class="fas fa-file-alt"></i>
                <p>暂无作品</p>
            </div>
        `;
    } else {
        // 确保每个作品都有id属性
        worksList = worksList.map((work, index) => {
            if (!work.id) {
                work.id = index + 1; // 使用索引作为临时id
            }
            return work;
        });

        // 排序Works（按时间倒序，如果有时间字段）
        if (worksList.length > 0 && worksList[0].time) {
            worksList.sort((a, b) => new Date(b.time) - new Date(a.time));
        }

        // 渲染Works列表
        worksList.forEach(work => {
            const workCard = document.createElement('div');
            workCard.className = 'work-card mb-4 border rounded-lg p-4 shadow-sm';
            workCard.innerHTML = `
  <div class="work-header">
    <h3 class="work-title">${work.title}</h3>
    <div class="work-actions">
      <button class="btn btn-secondary btn-sm" onclick="openWorkEditor(${work.id})">编辑</button>
      <button class="btn btn-danger btn-sm" onclick="deleteWork(${work.id})">删除</button>
    </div>
  </div>
  <p class="work-description">${work.description || '无描述'}</p>
  <div class="work-meta">
    ${work.url ? `<span>链接: <a href="${work.url}" target="_blank">${work.url}</a></span>` : ''}
  </div>
  ${work.image && work.image !== '#' ? `<div class="work-image mt-3"><img src="${work.image}" alt="${work.title}" style="max-width: 100%; max-height: 200px; border-radius: 4px;"></div>` : ''}
`;
            worksListContainer.appendChild(workCard);
        });
    }
}

// 打开Work编辑器
function openWorkEditor(workId = null) {
    currentEditingWorkId = workId;
    
    // 如果是编辑模式，加载Work内容
    if (workId) {
        // 尝试从缓存获取数据
        const cachedWorks = dataCache.getCache('works');
        
        if (cachedWorks) {
            // 从缓存中查找作品
            const work = cachedWorks.find(item => item.id == workId) || {};
            openWorkModal(work);
        } else {
            // 缓存无效时，重新请求数据
            fetch('../BlogMake.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                },
                body: 'action=get_works_list'
            })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        const works = data.data || [];
                        const work = works.find(item => item.id == workId) || {};
                        
                        // 更新缓存
                        dataCache.updateCache('works', works);
                        
                        openWorkModal(work);
                    } else {
                        showStatus('加载作品信息失败: ' + data.message, 'error');
                        // 即使失败也显示模态框
                        openWorkModal();
                    }
                })
                .catch(error => {
                    console.error('加载作品信息失败:', error);
                    showStatus('加载作品信息失败', 'error');
                    // 即使失败也显示模态框
                    openWorkModal();
                });
        }
    } else {
        // 新增模式，直接打开空模态框
        openWorkModal();
    }
}

// 打开作品模态框
function openWorkModal(workData = null) {
    // 使用模态框管理器打开模态框
    modalManager.open('work-modal', {
        title: workData ? '编辑作品' : '添加作品',
        data: workData ? {
            id: workData.id,
            title: workData.title,
            description: workData.description,
            link: workData.url, // 注意这里是link，因为表单字段是work-link
            image: workData.image
        } : null
    });
}

// 保存Work
function saveWork() {
    const title = document.getElementById('work-title').value;
    const description = document.getElementById('work-description').value;
    const url = document.getElementById('work-link').value;
    const image = document.getElementById('work-image').value;
    const workId = document.getElementById('work-id').value;

    // 验证必填项
    if (!title) {
        showStatus('标题不能为空', 'error');
        return;
    }

    // 准备作品数据
    const workData = {
        title: title,
        description: description,
        url: url,
        image: image
    };

    if (workId) {
        // 更新现有Work
        workData.id = workId;
        fetch('../BlogMake.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            body: 'action=update_work&workData=' + encodeURIComponent(JSON.stringify(workData))
        })
                        .then(response => response.json())
                        .then(saveData => {
                            if (saveData.success) {
                                showStatus('作品更新成功', 'success');
                                // 关闭模态框
                                modalManager.close('work-modal');
                                // 重新加载作品列表
                                loadWorksList();
                                currentEditingWorkId = null;
                            } else {
                                showStatus('作品更新失败: ' + saveData.message, 'error');
                            }
                        })
                        .catch(error => {
                            console.error('保存作品失败:', error);
                            showStatus('保存作品失败', 'error');
                        });
            
    } else {
        // 添加新作品
        fetch('../BlogMake.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            body: 'action=add_work&workData=' + encodeURIComponent(JSON.stringify(workData))
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                // 关闭模态框
                modalManager.close('work-modal');
                // 重新加载作品列表
                loadWorksList();
                // 显示成功提示
                showStatus('作品添加成功', 'success');
                currentEditingWorkId = null;
            } else {
                showStatus('作品添加失败: ' + data.message, 'error');
            }
        })
        .catch(error => {
            console.error('添加作品失败:', error);
            showStatus('添加作品失败', 'error');
        });
    }
}

// 删除Work
function deleteWork(workId) {
    if (!confirm('确定要删除这个作品吗？此操作无法撤销。')) {
        return;
    }

    fetch('../BlogMake.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
        },
        body: 'action=delete_work&id=' + workId
    })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                // 直接重新加载作品列表，不再尝试保存可能为空的列表
                loadWorksList();
                showStatus('作品删除成功', 'success');
            } else {
                showStatus('删除作品失败: ' + data.message, 'error');
            }
        })
        .catch(error => {
            console.error('删除作品失败:', error);
            showStatus('删除作品失败', 'error');
        });
}